﻿using System.Collections.Generic;
using Jayden.Dll.Entities.Common;
using Jayden.Dll.Web.Enums;
using Jayden.Dll.Web.HtmlControls;

namespace Jayden.Dll.Web.Controls.Edit
{
	public class ContactTable : DataTable<Contact>
	{
		public override void Load(System.Xml.XmlNode node, HtmlControlLoader loader)
		{
			base.Load(node, loader);

			CssProperties.Add("table-layout", "fixed");
			if (string.IsNullOrWhiteSpace(Id))
				Id = "contactTable";

			AddColumn(null, 20, delegate(Contact value, Column column, int index) { return OneControl(new Input(HtmlInputType.Checkbox, "contactIds", value.ContactId.ToString())); }, null);
			AddColumn("Date", 80, delegate(Contact value, Column column, int index) { return ParseText(value.CreationDate.ToShortDateString()); }, null);
			AddColumn("Email", 150, delegate(Contact value, Column column, int index) { return ParseText(value.Email); }, null);
			AddColumn("LastName", 150, delegate(Contact value, Column column, int index) { return ParseText(value.LastName); }, null);
			AddColumn("FirstName", 100, delegate(Contact value, Column column, int index) { return ParseText(value.FirstName); }, null);
			AddColumn("Title", 250, delegate(Contact value, Column column, int index) { return OneControl(new A(value.Title, "?viewContactId=" + value.ContactId)); }, null);

			CssProperties.Add("width", GetTableSizeFromColumns());
		}

		private void LoadFromContext(HttpHandlerContext context)
		{
			Clear();
			Th[] ths = AddHeaders();
			ths[0].AddControl(new Input(HtmlInputType.Checkbox, "all", null));
			ths[0].CssProperties.Add("text-align", "left");

			ContactDataAccess contactDataAccess = context.UnitOfWork.DataAccessManager.GetDataAccess<ContactDataAccess, Contact>();
			int totalRecords = 0;
			List<Contact> contacts = new List<Contact>(contactDataAccess.ReadByCategory(string.Empty, 0, int.MaxValue, out totalRecords));
			foreach (Contact description in contacts)
				AddTr(description);

		}

		public override void ProcessHtmlRequest(HttpHandlerContext context)
		{
			LoadFromContext(context);
			base.ProcessHtmlRequest(context);
		}

		public override void ProcessJsRequest(HttpHandlerContext context)
		{
			base.ProcessJsRequest(context);

			string id = Id;
			context.Js[id].AppendOnInit(@"
	$('#" + id + @"').on('click','input[name=""all""]',function() {
		var $this = $(this);
		if($this.is(':checked')) {
			$('#" + id + @" input[name=""contactIds""]').attr('checked','checked');
		} else {
			$('#" + id + @" input[name=""contactIds""]').removeAttr('checked');
		}
	});
");
		}

		public new Tr AddTr(Contact value)
		{
			Tr tr = base.AddTr(value);
			return tr;
		}
	}
}
